package com.china.zhuoyue.ui.ext

import android.app.Activity
import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.style.*
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.china.zhuoyue.ui.bean.TabEntity
import com.china.zhuoyue.ui.utils.Logger
import com.flyco.tablayout.CommonTabLayout
import com.flyco.tablayout.listener.CustomTabEntity
import com.google.android.material.tabs.TabLayout
import com.permissionx.guolindev.PermissionX
import com.yanzhenjie.permission.AndPermission

fun CommonTabLayout.tabData(tabs: FlycoTab.() -> Unit) {
    setTabData(FlycoTab().also(tabs).tabs)
}

class FlycoTab {
    val tabs = ArrayList<CustomTabEntity>()
    fun tab(title: String = "", selectedIcon: Int = 0, unSelectedIcon: Int = 0, tag: String? = null, extend: String? = null) {
        tabs.add(TabEntity(title, selectedIcon, unSelectedIcon, tag, extend))
    }
}

fun TabLayout.tabData(tabs: Tab.() -> Unit) {
    Tab().also(tabs).tabs.forEach {
        addTab(newTab().setText(it))
    }
}

class Tab {
    val tabs = ArrayList<String>()
    inline fun tab(text: () -> String) {
        tabs.add(text())
    }
}

fun TextView.textSpan(text: String?, spans: TextViewSpan.() -> Unit) {
    text?.let { newText ->
        if (newText.isNotEmpty()) {
            val spannableString = SpannableString(text)
            TextViewSpan().apply(spans).spans.forEach {
                val result = kotlin.runCatching {
                    val start: Int = newText.indexOf(it.spanText)
                    if (start != -1) {
                        val end: Int = start + it.spanText.length
                        spannableString.setSpan(it.span, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                    }
                }
                if (result.isFailure) {
                    Logger.e(result.exceptionOrNull())
                }
            }
            setText(spannableString)
        }
    }
}

class TextViewSpan {
    val spans: MutableList<ViewSpanEntity> = mutableListOf()
    var spanText: String = ""
    fun addBoldSpan() = spans.add(ViewSpanEntity(spanText, StyleSpan(Typeface.BOLD)))
    fun addForegroundColorSpan(color: Int) = spans.add(ViewSpanEntity(spanText, ForegroundColorSpan(color)))
    fun addAbsoluteSizeSpan(textSizePx: Int) = spans.add(ViewSpanEntity(spanText, AbsoluteSizeSpan(textSizePx, false)))
    fun addUnderlineSpan() = spans.add(ViewSpanEntity(spanText, UnderlineSpan()))
    fun addClickableSpan(clickableSpan: ClickableSpan) = spans.add(ViewSpanEntity(spanText, clickableSpan))

    inner class ViewSpanEntity(var spanText: String, var span: Any)
}

fun FragmentActivity.permissionRequest(dqPermissionRequest: DQPermissionRequest.() -> Unit) {
    andPermission(this, DQPermissionRequest().also(dqPermissionRequest))
}

fun Fragment.permissionRequest(dqPermissionRequest: DQPermissionRequest.() -> Unit) {
    andPermission(this, DQPermissionRequest().also(dqPermissionRequest))
}

fun andPermissionX(tag: Any, dqPermissionRequest: DQPermissionRequest) {
    (when (tag) {
        is FragmentActivity -> PermissionX.init(tag)
        is Fragment -> PermissionX.init(tag)
        else -> {
            Logger.e("tag不合法")
            null
        }
    })?.apply {
        permissions(dqPermissionRequest.permissions)
            .onExplainRequestReason { scope, deniedList ->
                scope.showRequestReasonDialog(deniedList, "核心权限需要授予", "授予", "取消")
            }
            .onForwardToSettings { scope, deniedList ->
                scope.showForwardToSettingsDialog(deniedList, "核心权限需要授予", "授予", "取消")
            }
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    dqPermissionRequest.granted?.invoke(grantedList)
                } else {
                    dqPermissionRequest.denied?.invoke(deniedList)
                }
            }
    }
}

fun andPermission(tag: Any, dqPermissionRequest: DQPermissionRequest) {
    var hasPermission = false
    when (tag) {
        is Context -> {
            hasPermission = AndPermission.hasPermissions(tag, dqPermissionRequest.permissions.toTypedArray())
            AndPermission.with(tag)
        }
        is Fragment -> {
            hasPermission = AndPermission.hasPermissions(tag, dqPermissionRequest.permissions.toTypedArray())
            AndPermission.with(tag)
        }
        is android.app.Fragment -> {
            hasPermission = AndPermission.hasPermissions(tag, dqPermissionRequest.permissions.toTypedArray())
            AndPermission.with(tag)
        }
        is Activity -> {
            hasPermission = AndPermission.hasPermissions(tag, dqPermissionRequest.permissions.toTypedArray())
            AndPermission.with(tag)
        }
        else -> {
            Logger.e("tag不合法")
            null
        }
    }?.let {
        if (!hasPermission) {
            it.runtime()
                .permission(dqPermissionRequest.permissions.toTypedArray())
                .onGranted {
                    dqPermissionRequest.granted?.invoke(it)
                }.onDenied {
                    dqPermissionRequest.denied?.invoke(it)
                }.start()
        } else {
            dqPermissionRequest.granted?.invoke(dqPermissionRequest.permissions)
        }
    }
}
typealias permissionGranted = ((List<String>) -> Unit)?

class DQPermissionRequest {
    val permissions = mutableListOf<String>()
    var granted: permissionGranted = null
    var denied: permissionGranted = null
    fun permission(permission: String) {
        permissions.add(permission)
    }

    fun onGranted(granted: permissionGranted) {
        this.granted = granted
    }

    fun onDenied(denied: permissionGranted) {
        this.denied = denied
    }
}


